angular.module("app", ["ui.router", "ngSanitize", "ngResource", "ui.bootstrap", "dx"]);
angular.module("app").config(["$stateProvider", "$urlRouterProvider", "$locationProvider", "$httpProvider", function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
    $httpProvider.defaults.withCredentials = true;
    $httpProvider.defaults.transformResponse = function (data, headersGetter, status) {
        if (status !== 200) {
            alert("服务器开了小差, 请刷新或联系管理员");
            sessionStorage.clear();
            location.href = "#/login";
            return;
        }
        if (headersGetter()["content-type"] == "application/json;charset=UTF-8") {
            data = angular.fromJson(data);
            if (location.hash == "#/login") return data;
            if (data.statusCode == -100) {
                alert("系统服务连接异常!");
                location.href = "#/login";
            } else if (data.statusCode == -1) {
                alert("用户未登录");
                location.href = "#/login";
            }
        }
        return data;
    };
    $urlRouterProvider.when("", "/login");
    $urlRouterProvider.otherwise("/home/404");
    $stateProvider
        .state("login", {
            url: "/login",
            views: {
                "mainContent": {
                    templateUrl: "template/login/login.html?tk=" + new Date().getTime(),
                    controller: "loginCtrl"
                }
            }
        })
        .state("home", {
            url: "/home",
            views: {
                "mainContent": {
                    templateUrl: "template/home/home.html?tk=" + new Date().getTime(),
                    controller: "homeCtrl"
                }
            },
            resolve: {
                "treeViewDataSource": ["org", function (org) {
                    return org.getTreeData({}, {test: 1}, function (data) {
                    }).$promise;
                }],
                "orgList": ["org","treeViewDataSource", function (org,treeViewDataSource) {
                    return org.getList({}, {orgId: JSON.parse(sessionStorage.userInfo).orgId}, function (data) {
                    }).$promise;
                }]
            }
        })
        .state("resetPassword", {
            url: "/resetPassword",
            views: {
                "mainContent": {
                    templateUrl: "template/resetPassword/resetPassword.html?tk=" + new Date().getTime(),
                    controller: "resetPassword.Ctrl"
                }
            }
        })
        .state("home.welcome", {
            url: "/welcome",
            views: {
                "viewContent": {
                    templateUrl: "template/home/welcome/welcome.html?tk=" + new Date().getTime(),
                    controller: "welcomeCtrl"
                }
            }
        })
        .state("home.welcome.group", {
            url: "/group",
            views: {
                "viewContent": {
                    templateUrl: "template/home/welcome/group/group.html?tk=" + new Date().getTime(),
                    controller: "welcome.group.Ctrl"
                }
            }
        })
        .state("home.welcome.volunteer", {
            url: "/volunteer",
            views: {
                "viewContent": {
                    templateUrl: "template/home/welcome/volunteer/volunteer.html?tk=" + new Date().getTime(),
                    controller: "welcome.volunteer.Ctrl"
                }
            }
        })
        .state("home.welcome.activity", {
            url: "/activity",
            views: {
                "viewContent": {
                    templateUrl: "template/home/welcome/activity/activity.html?tk=" + new Date().getTime(),
                    controller: "welcome.activity.Ctrl"
                }
            }
        })
        .state("home.welcome.time", {
            url: "/time",
            views: {
                "viewContent": {
                    templateUrl: "template/home/welcome/time/time.html?tk=" + new Date().getTime(),
                    controller: "welcome.time.Ctrl"
                }
            }
        })
        .state("home.setting", {
            url: "/setting",
            views: {
                "viewContent": {
                    templateUrl: "template/home/setting/setting.html?tk=" + new Date().getTime(),
                    controller: "settingCtrl"
                }
            }
        })
        .state("home.org", {
            url: "/org",
            abstract: true,
            views: {
                "viewContent": {
                    template: "<div ui-view='subview'><div/>"
                }
            }
        })
        .state("home.org.list", {
            url: "/list",
            views: {
                "subview": {
                    templateUrl: "template/home/org/list/list.html?tk=" + new Date().getTime(),
                    controller: "org.list.Ctrl"
                }
            }
        })
        .state("home.org.info", {
            url: "/info",
            views: {
                "subview": {
                    templateUrl: "template/home/org/info/info.html?tk=" + new Date().getTime(),
                    controller: "org.info.Ctrl"
                }
            }
        })
        .state("home.org.managerList", {
            url: "/managerList",
            views: {
                "subview": {
                    templateUrl: "template/home/org/managerList/managerList.html?tk=" + new Date().getTime(),
                    controller: "org.managerList.Ctrl"
                }
            }
        })
        .state("home.group", {
            url: "/group",
            abstract: true,
            views: {
                "viewContent": {
                    template: "<div ui-view='subview'><div/>"
                }
            }
        })
        .state("home.group.list", {
            url: "/list",
            views: {
                "subview": {
                    templateUrl: "template/home/group/list/list.html?tk=" + new Date().getTime(),
                    controller: "group.list.Ctrl"
                }
            }
        })
        .state("home.group.verify", {
            url: "/verify",
            views: {
                "subview": {
                    templateUrl: "template/home/group/verify/verify.html?tk=" + new Date().getTime(),
                    controller: "group.verify.Ctrl"
                }
            }
        })
        .state("home.passport", {
            url: "/passport",
            abstract: true,
            views: {
                "viewContent": {
                    template: "<div ui-view='subview'><div/>"
                }
            }
        })
        .state("home.passport.make", {
            url: "/make",
            views: {
                "subview": {
                    templateUrl: "template/home/passport/make/make.html?tk=" + new Date().getTime(),
                    controller: "passport.make.Ctrl"
                }
            }
        })
        .state("home.passport.allot", {
            url: "/make/:id",
            views: {
                "subview": {
                    templateUrl: "template/home/passport/make/allot.html?tk=" + new Date().getTime(),
                    controller: "passport.make.Ctrl"
                }
            }
        })
        .state("home.passport.send", {
            url: "/send",
            views: {
                "subview": {
                    templateUrl: "template/home/passport/send/send.html?tk=" + new Date().getTime(),
                    controller: "passport.send.Ctrl"
                }
            }
        })
        .state("home.passport.sent", {
            url: "/sent",
            views: {
                "subview": {
                    templateUrl: "template/home/passport/sent/sent.html?tk=" + new Date().getTime(),
                    controller: "passport.sent.Ctrl"
                }
            }
        })
        .state("home.passport.activate", {
            url: "/activate",
            views: {
                "subview": {
                    templateUrl: "template/home/passport/activate/activate.html?tk=" + new Date().getTime(),
                    controller: "passport.activate.Ctrl"
                }
            }
        })
        .state("home.passport.logout", {
            url: "/logout",
            views: {
                "subview": {
                    templateUrl: "template/home/passport/logout/logout.html?tk=" + new Date().getTime(),
                    controller: "passport.logout.Ctrl"
                }
            }
        })
        .state("home.group.base", {
            url: "/base",
            views: {
                "subview": {
                    templateUrl: "template/home/group/base/base.html?tk=" + new Date().getTime(),
                    controller: "group.base.Ctrl"
                }
            }
        })
        .state("home.group.baseDetail", {
            url: "/base/:id",
            views: {
                "subview": {
                    templateUrl: "template/home/group/base/base-detail.html?tk=" + new Date().getTime(),
                    controller: "group.base.Ctrl"
                }
            }
        })
        .state("home.group.volunteerList", {
            url: "/volunteerList/:groupId",
            views: {
                "subview": {
                    templateUrl: "template/home/group/volunteerList/volunteerList.html?tk=" + new Date().getTime(),
                    controller: "group.volunteerList.Ctrl"
                }
            }
        })
        .state("home.group.activityList", {
            url: "/activityList/:userId",
            views: {
                "subview": {
                    templateUrl: "template/home/group/activityList/activityList.html?tk=" + new Date().getTime(),
                    controller: "group.activityList.Ctrl"
                }
            }
        })
        .state("home.group.info", {
            url: "/info/:groupId",
            views: {
                "subview": {
                    templateUrl: "template/home/group/info/info.html?tk=" + new Date().getTime(),
                    controller: "group.info.Ctrl"
                }
            }
        })
        .state("home.user", {
            url: "/user",
            abstract: true,
            views: {
                "viewContent": {
                    template: "<div ui-view='subview'><div/>"
                }
            }
        })
        .state("home.user.changePassword", {
            url: "/changePassword",
            views: {
                "subview": {
                    templateUrl: "template/home/user/changePassword/changePassword.html?tk=" + new Date().getTime(),
                    controller: "user.changePassword.Ctrl"
                }
            }
        });
    $httpProvider.interceptors.push("timestampMarker");
}]);
angular.module("app").run(["$rootScope", function($rootScope) {
    if(location.host.indexOf("localhost") >= 0){
        $rootScope.sysOrigin = "http://test.dakaqi.cn:9082";
    }
    else{
        $rootScope.sysOrigin = "/approve";
    }
    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
        if(toState.name.indexOf("home") >= 0 && !sessionStorage.userInfo){
            event.preventDefault();
            location.href = "#/login";
        }
    })
}]);
/**
 * Created by cjd on 2016/5/4.
 */
angular.module("app").factory("timestampMarker", ["$rootScope", "$timeout", function ($rootScope, $timeout) {
    return {
        request: function (config) {
            var headersGetter = config.headers;
            if ((headersGetter["Accept"] && headersGetter["Accept"].split(",")[0]) == "application/json" && config["url"].indexOf("template") < 0) {
                $rootScope.loading = true;
                config.requestTimestamp = new Date().getTime();
                config.url = $rootScope.sysOrigin + config.url;
            }
            return config;
        },
        response: function (response) {
            // $timeout(function () {
            //     $rootScope.loading = false;
            // }, 500);
            response.config.responseTimestamp = new Date().getTime();
            return response;
        }
    };
}]);
angular.module("app")
    .factory("User", ["$resource", function ($resource) {
        return $resource("", {}, {
            Login: {
                cache: false,
                method: "POST",
                url: "/user/login",
                isArray: false
            },
            sendSMS: {
                cache: false,
                method: "POST",
                url: "/user/sendCode",
                isArray: false
            },
            checkPassword: {
                cache: false,
                method: "POST",
                url: "/user/checkPassword",
                isArray: false
            },
            updatePassword: {
                cache: false,
                method: "POST",
                url: "/user/updatePassword",
                isArray: false
            },
            resetPassword: {
                cache: false,
                method: "POST",
                url: "/user/resetPassword",
                isArray: false
            },
            getList: {
                cache: false,
                method: "POST",
                url: "/user/listByOrgId",
                isArray: false
            },
            saveUser: {
                cache: false,
                method: "POST",
                url: "/user/save",
                isArray: false
            },
            updateStatus: {
                cache: false,
                method: "POST",
                url: "/user/updateStatus",
                isArray: false
            }
        });
    }])
    .factory("org", ["$resource", function ($resource) {
        return $resource("", {}, {
            count: {
                cache: false,
                method: "POST",
                url: "/index/count",
                isArray: false
            },
            getTreeData: {
                cache: false,
                method: "POST",
                url: "/org/test",
                isArray: false
            },
            updateStatus: {
                cache: false,
                method: "POST",
                url: "/org/updateStatus",
                isArray: false
            },
            saveOrg: {
                cache: false,
                method: "POST",
                url: "/org/save",
                isArray: false
            },
            getList: {
                cache: false,
                method: "POST",
                url: "/org/list",
                isArray: false
            }
        });
    }])
    .factory("group", ["$resource", function ($resource) {
        return $resource("", {}, {
            listByOrg: {
                cache: false,
                method: "POST",
                url: "/group/listByOrg",
                isArray: false
            },
            volListById: {
                cache: false,
                method: "POST",
                url: "/group/volListById",
                isArray: false
            },
            getGroupInfo: {
                cache: false,
                method: "POST",
                url: "/group/info",
                isArray: false
            }
        });
    }])
    .factory("activitySign", ["$resource", function ($resource) {
        return $resource("", {}, {
            listByUser: {
                cache: false,
                method: "POST",
                url: "/activitySign/listByUser",
                isArray: false
            }
        });
    }])
    .factory("passport", ["$resource", function ($resource) {
        return $resource("", {}, {
            getList: {
                cache: false,
                method: "POST",
                url: "/passport/queryList",
                isArray: false
            },
            sentList: {
                cache: false,
                method: "POST",
                url: "/passport/queryByDate",
                isArray: false
            },
            getDistrict: {
                cache: false,
                method: "POST",
                url: "/passport/queryArea",
                isArray: false
            },
            getAddress: {
                cache: false,
                method: "POST",
                url: "/passport/queryAddressList",
                isArray: false
            },
            allotAddress: {
                cache: false,
                method: "POST",
                url: "/passport/changeBaseAddress",
                isArray: false
            }
        });
    }])
    .factory("groupVerify", ["$resource", function ($resource) {
        return $resource("", {}, {
            getList: {
                cache: false,
                method: "POST",
                url: "/orgVerify/list",
                isArray: false
            },
            checkFail: {
                cache: false,
                method: "POST",
                url: "/orgVerify/checkFail",
                isArray: false
            },
            checkSuccess: {
                cache: false,
                method: "POST",
                url: "/orgVerify/checkSuccess",
                isArray: false
            }
        });
    }])
    .factory("groupBase", ["$resource", function ($resource) {
        return $resource("", {}, {
            getList: {
                cache: false,
                method: "POST",
                url: "/address/queryList",
                isArray: false
            },
            getDetail: {
                cache: false,
                method: "POST",
                url: "/address/queryDetail",
                isArray: false
            },
            sendComment: {
                cache: false,
                method: "POST",
                url: "/address/approve",
                isArray: false
            }
        });
    }])
;
angular.module("app").controller("welcomeCtrl", ["$scope", "$http", "$timeout","org", function($scope, $http, $timeout,org) {
    $scope.orgCountVo = {};
    $scope.getMonthList = function (number) {
        var monList = [];
        var d = new Date();
        var currYear = d.getFullYear();
        var currMon = d.getMonth();  // 获取上一个月份数值，此处不需要+1
        for(var i = 0; i < number; i++){
            if(currMon < 10){
                monList.push("" + currYear + "-0" + currMon);
            }else{
                monList.push("" + currYear + "-" + currMon);
            }
            currMon -= 1; // 获取上一个月份
            if(currMon == 0){
                currYear -= 1;
                currMon = 12;
            }
        }
        return monList.sort();
    };

    org.count({}, {test:1}, function (data) {
        if (data.statusCode == 0) {
            $scope.orgCountVo = data.data.orgCountVo;
            $scope.activityList = data.data.activityStr.split(",");
            $scope.timeList = data.data.timeStr.split(",");
            $scope.volunteerList = data.data.volunteerStr.split(",");
            var dataSource = [];
            $scope.getMonthList(12).forEach(function (item,index) {
                var obj = {};
                obj.Month = item;
                obj.volunteer = +$scope.volunteerList[index];
                obj.time = +$scope.timeList[index];
                obj.activity = +$scope.activityList[index];
                dataSource.push(obj);
            });
            $scope.volunteerChartConfig.dataSource = $scope.activityChartConfig.dataSource = $scope.timeChartConfig.dataSource = dataSource;
        } else {
            alert(data.statusMessage)
        }
    });

    $scope.volunteerChartConfig = {
        bindingOptions: {
            dataSource: "volunteerChartConfig.dataSource"
        },
        dataSource:[],
        commonSeriesSettings: {
            argumentField: "Month",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        series: [
            { valueField: "volunteer", name: "志愿者(人)" }
        ],
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center",
            itemTextPosition: "bottom"
        },
        title: {
            text: "志愿者增量图"
            // subtitle: {
            //     text: "(Millions of Tons, Oil Equivalent)"
            // }
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: arg.valueText + "人"
                };
            }
        }
    };

    $scope.activityChartConfig = {
        bindingOptions: {
            dataSource: "activityChartConfig.dataSource"
        },
        dataSource:[],
        commonSeriesSettings: {
            argumentField: "Month",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        series: [
            { valueField: "activity", name: "活动(次)" }
        ],
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center",
            itemTextPosition: "bottom"
        },
        title: {
            text: "活动增量图"
            // subtitle: {
            //     text: "(Millions of Tons, Oil Equivalent)"
            // }
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: arg.valueText + "次"
                };
            }
        }
    };

    $scope.timeChartConfig = {
        bindingOptions: {
            dataSource: "timeChartConfig.dataSource"
        },
        dataSource:[],
        commonSeriesSettings: {
            argumentField: "Month",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        series: [
            { valueField: "time", name: "公益时间(分钟)" }
        ],
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center",
            itemTextPosition: "bottom"
        },
        title: {
            text: "公益时间增量图"
            // subtitle: {
            //     text: "(Millions of Tons, Oil Equivalent)"
            // }
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: arg.valueText + "分钟"
                };
            }
        }
    };
}]);

/**
 * Created by cjd on 2016/6/13.
 */
angular.module("app").controller("settingCtrl", ["$scope", "$http", "org", function ($scope, $http, org) {
    $scope.saveOrg = function () {
        if(confirm("是否确定执行该操作?")){
            delete $scope.orgInfo.createTime;
            org.saveOrg({}, $scope.orgInfo, function (data) {
                if (data.statusCode == 0) {
                    alert("操作成功!");
                }
            });
        }
    };
    $scope.orgInfo = $scope.userInfo.organization;
    $scope.provinceChange = function(){
        $scope.orgInfo.city = city.filter(function(item){
            return item.ProID == $scope.orgInfo.province;
        })[0].CityID;
    };
    $scope.cityChange = function(){
        $scope.orgInfo.county = District.filter(function(item){
            return item.CityID == $scope.orgInfo.city;
        })[0].Id;
    }
}]);
/**
 * Created by cjd on 2016/6/12.
 */
angular.module("app").controller("group.activityList.Ctrl", ["$scope", "activitySign","$stateParams", function ($scope,activitySign,$stateParams) {
    $scope.activityGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "activityGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "realName",
            alignment: "center",
            width:200,
            caption: "昵称"
        }, {
            dataField: "nickName",
            alignment: "center",
            width:200,
            caption: "真名"
        }, {
            dataField: "name",
            alignment: "center",
            caption: "活动名称"
        }, {
            dataField: "times",
            alignment: "center",
            width:200,
            caption: "公益时间"
        }]
    };
    $scope.getList = function (userId) {
        activitySign.listByUser({}, {userId: userId}, function (data) {
            if (data.statusCode == 0) {
                $scope.activityGridConfig.dataSource = data.data;
            }
        });
    };
    $scope.getList($stateParams.userId);
}]);
/**
 * Created by cjd on 2016/6/16.
 */
angular.module("app").controller("group.info.Ctrl", ["$scope", "group","$stateParams", function ($scope, group,$stateParams) {
    $scope.getGroupInfo = function(groupId){
        group.getGroupInfo({}, {id: groupId}, function (data) {
            if (data.statusCode == 0) {
                $scope.groupInfo = data.data;
            }
        });
    };
    if($stateParams.groupId){
        $scope.getGroupInfo($stateParams.groupId);
    }
}]);
/**
 * Created by cjd on 2016/5/10.
 */
angular.module("app").controller("group.list.Ctrl", ["$scope", "group", "$timeout", function ($scope, group, $timeout) {
    $scope.groupGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "groupGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "name",
            alignment: "center",
            caption: "基地名称"
        }, {
            dataField: "times",
            alignment: "center",
            caption: "公益时间"
        }, {
            dataField: "volunteers",
            alignment: "center",
            width:80,
            caption: "成员数量"
        }, {
            dataField: "actvitys",
            alignment: "center",
            width:80,
            caption: "活动数量"
        }, {
            dataField: "monitor",
            alignment: "center",
            caption: "负责人"
        }, {
            dataField: "phone",
            alignment: "center",
            caption: "联系电话"
        }, {
            dataField: "delStatus",
            alignment: "center",
            width:60,
            cellTemplate: "statusCellTemplate",
            caption: "状态"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "操作"
        }]
    };
    $scope.orgParent = $scope.$parent.treeViewDataSource[0].orgId;
    $scope.getList = function (orgId) {
        group.listByOrg({}, {orgId: orgId}, function (data) {
            if (data.statusCode == 0) {
                $scope.groupGridConfig.dataSource = data.data;
            }
        });
    };
    $scope.treeViewConfig = angular.copy($scope.$parent.treeViewConfig);
    $scope.treeViewConfig.onItemClick = function (e) {
        $scope.getList(e.itemData.orgId);
        $scope.orgParent = e.itemData.orgId;
        $scope.groupInfo = {};
    };

    $scope.showGroupInfo = function (groupInfo) {
        $scope.groupInfo = groupInfo;
    };
    $scope.showVolunteerList = function (groupInfo) {
        location.href = "#/home/group/volunteerList/" + groupInfo.id;
    };
    $scope.getList($scope.$parent.treeViewDataSource[0].orgId);
}]);
/**
 * Created by cjd on 2016/6/14.
 */
angular.module("app").controller("group.verify.Ctrl", ["$scope", "groupVerify","$stateParams", function ($scope, groupVerify,$stateParams) {
    $scope.statusEnum = {"0":"待审核","-1":"已拒绝","2":"已通过"};
    $scope.columns = [
        {
        dataField: "groupName",
        alignment: "center",
        caption: "申请基地"
    }, 
        {
        dataField: "createTime",
        alignment: "center",
        cellTemplate: "createTimeCellTemplate",
        caption: "申请日期"
    },  
        {
        dataField: "status",
        alignment: "center",
        cellTemplate: "statusCellTemplate",
        width: 60,
        caption: "状态"
    }, 
        null, 
        {
        dataField: "operation",
        alignment: "center",
        cellTemplate: "operationCellTemplate",
        caption: "操作"
    }
    ];
    $scope.orgVerifyListGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "orgVerifyListGridConfig.dataSource",
            columns: "columns"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据"
    };
    $scope.orgVerifyHistoryGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "orgVerifyHistoryGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        // searchPanel: {
        //     visible: true,
        //     width: 200,
        //     placeholder: "输入关键字进行查询"
        // },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "createTime",
            alignment: "center",
            cellTemplate: "createTimeCellTemplate",
            caption: "申请日期"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "审核"
        }]
    };
    $scope.changeStatus = function(status){
        if($scope.dataSource && $scope.dataSource.length){
            $scope.orgVerifyListGridConfig.dataSource = $scope.dataSource.filter(function(item){
                return item.status == status;
            });
            if(status == 0 && $scope.columns[3]){
                delete $scope.columns[3]
            }
            else if(status != 0 && !$scope.columns[3]){
                $scope.columns[3] = {
                    dataField: "verifyTime",
                    alignment: "center",
                    cellTemplate: "verifyTimeCellTemplate",
                    caption: "审核日期"
                }
            }
            $scope.orgVerifyListCount = $scope.orgVerifyListGridConfig.dataSource.length;
            for (var i in $scope.$parent.verifyTabs) {
                $scope.$parent.verifyTabs[i] = false;
            }
            $scope.$parent.verifyTabs[status] = true;
        }
    };
    $scope.showGroupInfo = function (applyInfo) {
        location.href = "#/home/group/info/" + applyInfo.groupId;
    };
    $scope.Verify = function(applyInfo){
        if(applyInfo.status == 0){
            $scope.applyInfo = angular.copy(applyInfo);
        }
        $scope.showVerifyHistory(applyInfo);
    };
    $scope.showVerifyHistory = function(applyInfo){
        $scope.type = "view";
        $scope.orgVerifyHistoryGridConfig.dataSource = $scope.dataSource.filter(function(item){
            return item.groupId == applyInfo.groupId;
        });
        $scope.orgVerifyHistoryGridConfig.dataSource.sort(function(a,b){return b.verifyTime - a.verifyTime});
    };
    $scope.getList = function(){
        groupVerify.getList({}, {test: 1}, function (data) {
            if (data.statusCode == 0) {
                $scope.dataSource = data.data;
                $scope.orgVerifyListGridConfig.dataSource = $scope.dataSource.filter(function(item){
                    return item.status == 0;
                });
                $scope.orgVerifyListCount = $scope.orgVerifyListGridConfig.dataSource.length;
            }
        });
    };
    $scope.check = function(){
        if(confirm("是否确定执行该操作?")){
            if($scope.applyInfo.status == -1){
                $scope.checkFail($scope.applyInfo);
            }
            else if($scope.applyInfo.status == 2){
                $scope.checkSuccess($scope.applyInfo);
            }
        }
    };
    $scope.checkSuccess = function(applyInfo){
        groupVerify.checkSuccess({}, {id: applyInfo.id,remark:applyInfo.remark}, function (data) {
            if (data.statusCode == 0) {
                alert("操作成功!");
                $scope.getList();
                $scope.applyInfo = {};
                $scope.type = "list";
            }
            else{
                alert(data.statusMessage)
            }
        });
    };
    $scope.checkFail = function(applyInfo){
        groupVerify.checkFail({}, {id: applyInfo.id,remark:applyInfo.remark}, function (data) {
            if (data.statusCode == 0) {
                alert("操作成功!");
                $scope.getList();
                $scope.applyInfo = {};
                $scope.type = "list";
            }
            else{
                alert(data.statusMessage)
            }
        });
    };
    $scope.getList();
}]);
/**
 * Created by cjd on 2016/6/12.
 */
angular.module("app").controller("group.volunteerList.Ctrl", ["$scope", "group","$stateParams", function ($scope, group,$stateParams) {
    $scope.volunteerGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "volunteerGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "realName",
            alignment: "center",
            caption: "姓名"
        }, {
            dataField: "mobile",
            alignment: "center",
            caption: "手机号"
        }, {
            dataField: "acts",
            alignment: "center",
            width:80,
            caption: "活动次数"
        }, {
            dataField: "times",
            alignment: "center",
            width:80,
            caption: "公益时间"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "操作"
        }]
    };
    $scope.getList = function (groupId) {
        group.volListById({}, {id: groupId}, function (data) {
            if (data.statusCode == 0) {
                $scope.volunteerGridConfig.dataSource = data.data;
            }
        });
    };

    $scope.showActivityList = function (volunteerInfo) {
        location.href = "#/home/group/activityList/" + volunteerInfo.id;
    };
    $scope.getList($stateParams.groupId);
}]);
/**
 * Created by cjd on 2016/6/9.
 */
angular.module("app").controller("user.changePassword.Ctrl", ["$scope", "$http", "User", function ($scope, $http, User) {
    $scope.editPassword = function(){
        if($scope.newPW != $scope.newPW2){
            alert("两次输入的密码不一致,请重新输入!");
            return;
        }
        User.checkPassword({}, {password: $scope.password}, function (data) {
            if (data.statusCode == 0) {
                User.updatePassword({}, {password: $scope.newPW2}, function (data) {
                    if (data.statusCode == 0) {
                        alert("修改密码成功,请重新登录!");
                        sessionStorage.clear();
                        location.href = "#/login";
                    } else {
                        alert("原始密码错误,请重新输入!")
                    }
                })
            } else {
                alert("原始密码错误,请重新输入!")
            }
        })
    };
}]);
/**
 * Created by cjd on 2016/6/14.
 */
angular.module("app").controller("group.base.Ctrl", ["$scope", "groupBase", '$state', "$stateParams", function ($scope, groupBase, $state, $stateParams) {
    if($stateParams.id){
        groupBase.getDetail({}, {id: $stateParams.id}, function (data) {
            $scope.baseDetail = data.data
        });
    }else{
        groupBase.getList({}, {}, function (data) {
            $scope.baseList = data.data
        });
    }
    $scope.sendComment = function (status) {
        if(status == 2){
            var val = $('.add-score').val(), numberReg = /^\d+$/
            if(val < 1 || val > 10 || !numberReg.test(val)){
                alert('请输入有效分数,且范围为1-10分')
                return
            }
            groupBase.sendComment({}, {id: $stateParams.id, score: val}, function (data) {
                if(data.statusCode == 0){
                    alert(data.statusMessage)
                    $state.go('home.group.base')
                }else{
                    alert(data.statusMessage)
                }
            })
        }else{
            if($('.add-remark').val() == ''){
                alert('请填写您的意见')
                return
            }
            groupBase.sendComment({}, {id: $stateParams.id, status: status, remark: $('.add-remark').val()}, function (data) {
                if(data.statusCode == 0){
                    alert(data.statusMessage)
                    $state.go('home.group.base')
                }else{
                    alert(data.statusMessage)
                }
            })
        }
    }
}]);
/**
 * Created by cjd on 2016/6/9.
 */
angular.module("app").controller("org.info.Ctrl", ["$scope", "$http", "org", function ($scope, $http, org) {
    $scope.viewOrginfo = function(data){
        $('select').attr('disabled',true)
        var responseData = JSON.parse(sessionStorage.getItem("areainfo")), $province = $('#provinceData'), $city = $('#cityData'), $area = $('#areaData'), $street = $('#streetData'), $committee = $('#committeeData'), jurisdiction = data.jurisdiction
        var userProvinceId = jurisdiction.substring(0,2)+'0000', userCityId = jurisdiction.substring(0,4)+'00', userAreaId = jurisdiction.substring(0,6), userStreetId = jurisdiction.substring(0,9)+'000', userCommitteeId = jurisdiction.substring(0,12)
        if(jurisdiction.length > 6){
            $('.street-box').show()
        }else{
            $('.street-box').hide()
        }
        $.each(responseData.data.regionList, function(index,val){
            if(val.levelType == 1){
                if(val.id == userProvinceId){
                    $("<option value="+val.id+" data-parentId="+val.parentId+" selected>"+val.name+"</option>").appendTo($province)
                }
            }
            if(val.parentId == userProvinceId && val.levelType == 2) {
                if(val.id == userCityId){
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($city)
                }
            }
            if(val.parentId == userCityId && val.levelType == 3) {
                if(val.id == userAreaId){
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($area)
                }
            }
        })
        $.each(responseData.data.countyList, function(index,val){
            if(val.parentId == userAreaId && val.countrysideType == 0) {
                if(val.code == userStreetId){
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($street)
                }
            }
            if(val.parentId == userStreetId && val.countrysideType != 0) {
                if(val.code == userCommitteeId){
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($committee)
                }
            }
        })
    }
    $scope.treeViewConfig = angular.copy($scope.$parent.treeViewConfig);
    $scope.treeViewConfig.onItemClick = function(e){
        $scope.orgInfo = e.itemData;
        $scope.viewOrginfo($scope.orgInfo)
    };
    $scope.orgInfo = $scope.$parent.treeViewDataSource[0];
    $scope.viewOrginfo($scope.orgInfo)
}]);
/**
 * Created by cjd on 2016/6/7.
 */
angular.module("app").controller("org.list.Ctrl", ["$scope", "$http", "org", function ($scope, $http, org) {
    $scope.orgGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "orgGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "orgName",
            alignment: "center",
            caption: "组织名称"
        }, {
            dataField: "onePass",
            alignment: "center",
            caption: "一号通"
        }, {
            dataField: "orgCode",
            alignment: "center",
            width: 80,
            caption: "组织编码"
        }, {
            dataField: "principal",
            alignment: "center",
            caption: "联系人"
        }, {
            dataField: "phone",
            alignment: "center",
            caption: "联系电话"
        }, {
            dataField: "status",
            alignment: "center",
            cellTemplate: "statusCellTemplate",
            width: 60,
            caption: "状态"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "操作"
        }]
    };
    $scope.orgParent = $scope.$parent.treeViewDataSource[0].orgId;
    $scope.getList = function (orgId) {
        org.getList({}, {orgId: orgId}, function (data) {
            if (data.statusCode == 0) {
                $scope.orgGridConfig.dataSource = data.data.filter(function(item){
                    return item.orgId != item.orgParent
                });
            }
        });
    };
    $scope.updateOrgStatus = function (orgInfo) {
        org.updateStatus({}, {orgId: orgInfo.orgId}, function (data) {
            if (data.statusCode == 0) {
                if (orgInfo.status == 10) {
                    orgInfo.status = 20;
                }
                else {
                    orgInfo.status = 10;
                }
                alert("更新成功!")
            }
            else {
                alert(data.statusMessage)
            }
        });
    };
    $scope.treeViewConfig = angular.copy($scope.$parent.treeViewConfig);
    $scope.treeViewConfig.onItemClick = function (e) {
        $scope.getList(e.itemData.orgId);
        $scope.orgParent = e.itemData.orgId;
        $scope.orgInfo = {};
    };
    $scope.showOrgInfo = function (orgInfo) {
        $scope.orgInfo = orgInfo;
        $scope.type = "view";
        $scope.provinceChange("view");
        $scope.cityChange("view");
        $('select').attr('disabled',true)
        var responseData = JSON.parse(sessionStorage.getItem("areainfo")), $province = $('#provinceData'), $city = $('#cityData'), $area = $('#areaData'), $street = $('#streetData'), $committee = $('#committeeData'), jurisdiction = orgInfo.jurisdiction
        var userProvinceId = jurisdiction.substring(0,2)+'0000', userCityId = jurisdiction.substring(0,4)+'00', userAreaId = jurisdiction.substring(0,6), userStreetId = jurisdiction.substring(0,9)+'000', userCommitteeId = jurisdiction.substring(0,12)
        if(jurisdiction.length > 6){
            $('.street-box').show()
        }else{
            $('.street-box').hide()
        }
        $.each(responseData.data.regionList, function(index,val){
            if(val.levelType == 1){
                if(val.id == userProvinceId){
                    $("<option value="+val.id+" data-parentId="+val.parentId+" selected>"+val.name+"</option>").appendTo($province)
                }
            }
            if(val.parentId == userProvinceId && val.levelType == 2) {
                if(val.id == userCityId){
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($city)
                }
            }
            if(val.parentId == userCityId && val.levelType == 3) {
                if(val.id == userAreaId){
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($area)
                }
            }
        })
        $.each(responseData.data.countyList, function(index,val){
            if(val.parentId == userAreaId && val.countrysideType == 0) {
                if(val.code == userStreetId){
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($street)
                }
            }
            if(val.parentId == userStreetId && val.countrysideType != 0) {
                if(val.code == userCommitteeId){
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($committee)
                }
            }
        })
    };
    $scope.editOrgInfo = function (orgInfo) {
        $scope.orgInfo = orgInfo;
        $scope.type = "edit";
        $scope.provinceChange("view");
        $scope.cityChange("view");
        $('select').attr('disabled',false)
        var jurisdiction = orgInfo.jurisdiction
        var userProvinceId = jurisdiction.substring(0,2)+'0000', userCityId = jurisdiction.substring(0,4)+'00', userAreaId = jurisdiction.substring(0,6), userStreetId = jurisdiction.substring(0,9)+'000', userCommitteeId = jurisdiction.substring(0,12)
        var responseData = JSON.parse(sessionStorage.getItem("areainfo")), $province = $('#provinceData'), $city = $('#cityData'), $area = $('#areaData'), $street = $('#streetData'), $committee = $('#committeeData')
        $province.empty().append('<option value=0>请选择</option>')
        $.each(responseData.data.regionList, function(index,val){
            if(userProvinceId == 310000){
                $('.street-box').fadeIn()
            }
            if(val.levelType == 1){
                if(val.id == userProvinceId){
                    $("<option value="+val.id+" data-parentId="+val.parentId+" selected>"+val.name+"</option>").appendTo($province)
                }else{
                    $("<option value="+val.id+" data-parentId="+val.parentId+">"+val.name+"</option>").appendTo($province)
                }

            }
            if(val.parentId == userProvinceId && val.levelType == 2) {
                if(val.id == userCityId){
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($city)
                }else{
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($city)
                }

            }
            if(val.parentId == userCityId && val.levelType == 3) {
                if(val.id == userAreaId){
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($area)
                }else{
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($area)
                }

            }
        })
        $.each(responseData.data.countyList, function(index,val){
            if(val.parentId == userAreaId && val.countrysideType == 0) {
                if(val.code == userStreetId){
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($street)
                }else{
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($street)
                }

            }
            if(val.parentId == userStreetId && val.countrysideType != 0) {
                if(val.code == userCommitteeId){
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + " selected>" + val.name + "</option>").appendTo($committee)
                }else{
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($committee)
                }

            }
        })
        $province.on('change',function(){
            var id = $(this).val();
            $city.empty().append('<option value="0">请选择</option>')
            $area.empty().append('<option value="0">请选择</option>')
            $street.empty().append('<option value="0">请选择</option>')
            $committee.empty().append('<option value="0">请选择</option>')
            if(id == 310000){
                $('.street-box').show()
            }else{
                $('.street-box').hide()
            }
            $.each(responseData.data.regionList, function(index,val){
                if(val.parentId == id && val.levelType == 2) {
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($city)
                }
            })
            $('input[name="jurisdiction"]').val(id)
        })
        $city.on('change',function(){
            var id = $(this).val();
            $area.empty().append('<option value="0">请选择</option>')
            $street.empty().append('<option value="0">请选择</option>')
            $committee.empty().append('<option value="0">请选择</option>')
            $.each(responseData.data.regionList, function(index,val){
                if(val.parentId == id && val.levelType == 3) {
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($area)
                }
            })
            $('input[name="jurisdiction"]').val(id)
        })
        $area.on('change',function(){
            var id = $(this).val();
            $street.empty().append('<option value="0">请选择</option>')
            $committee.empty().append('<option value="0">请选择</option>')
            $.each(responseData.data.countyList, function(index,val){
                if(val.parentId == id && val.countrysideType == 0) {
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($street)
                }
            })
            $('input[name="jurisdiction"]').val(id)
        })
        $street.on('change',function(){
            var id = $(this).val();
            $committee.empty().append('<option value="0">请选择</option>')
            $.each(responseData.data.countyList, function(index,val){
                if(val.parentId == id && val.countrysideType != 0) {
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($committee)
                }
            })
            $('input[name="jurisdiction"]').val(id)
        })
        $committee.on('change',function(){
            var id = $(this).val();
            $('input[name="jurisdiction"]').val(id)
        })
    };
    $scope.saveOrg = function () {
        $scope.orgInfo.jurisdiction = $('#jurisdiction').val()
        //if($scope.isSocialCreditCode($scope.orgInfo.orgCode)){
            if(confirm("是否确定执行该操作?")){
                delete $scope.orgInfo.createTime;
                org.saveOrg({}, $scope.orgInfo, function (data) {
                    if (data.statusCode == 0) {
                        alert("操作成功!");
                        location.reload(true)
                    }
                });
            }
        //}
        //else{
        //    alert("机构代码/信用代码有误,请重新输入!")
        //}
    };
    $scope.isSocialCreditCode = function (code) {
        if (code.length != 18) {
            return false;
        }//必须是18位
        //登记管理部门代码1位
        var first = code.substring(0, 1);
        if (!/^[1,5,9,Y]{1}$/.test(first)) {
            return false;
        }//第一位数必须是以1，5，9或Y开头

        //机构类别代码1位
        var second = code.substring(1, 2);
        switch (first) {
            case "1" :
                if (!/^[1,2,3,9]$/.test(second)) {
                    return false;
                };
                break;//机构编制
            case "5" :
                if (!/^[1,2,3,9]$/.test(second)) {
                    return false;
                };
                break;//民政
            case "9" :
                if (!/^[1,2,3]$/.test(second)) {
                    return false;
                };
                break;//工商
            case "Y" :
                if (!/^[1]$/.test(second)) {
                    return false;
                };
                break;//其他
        }

        //登记管理机关行政区划码6位
        var xz = code.substring(2, 8);
        if (!/^[0-9]{6}$/.test(xz)) {
            return false;
        }

        //主体标识码（组织机构代码）9位
        var jg = code.substring(8, 17);
        if (!/^[0-9,A-H,J-N,P-R,T-U,W-Y]{9}$/.test(jg)) {
            return false;
        }//阿拉伯数字或者大写英语字母（不含I,O,Z,S,V）

        //第18位校验码
        var et = code.substring(17);

        /**计算第18位校证码*/
        //17位Ci的值
        var dmj = "0123456789ABCDEFGHJKLMNPQRTUWXY";
        var dmjv = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30);//字符集对应的值
        var Ci = new Array(17);
        for (var i = 0; i < 17; i++) {//17位
            var val = code.charAt(i);
            var indx = dmj.indexOf(val);
            Ci[i] = dmjv[indx];
        }
        //加权因子Wi
        var Wi = new Array(1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28);
        //Ci*Wi
        var CWi = new Array(17);
        var total = new Number(0);
        for (var i = 0; i < 17; i++) {
            var val = Ci[i] * Wi[i];
            CWi[i] = val;
            total += val;
        }
        var index = total % 31;
        var jm = "";
        if (index == 0) {
            jm = "0";
        } else {
            jm = dmj.charAt(31 - total % 31);
        }
        if (jm != et) {
            return false;
        }
        return true;
    };
    $scope.updateStatus = function (orgInfo) {
        if(confirm("是否确定执行该操作?")){
            $scope.updateOrgStatus(orgInfo);
        }
    };
    $scope.getList($scope.$parent.treeViewDataSource[0].orgId);
    $scope.createOrg = function () {
        $scope.type = "edit";
        $scope.orgInfo = {orgParent:$scope.orgParent,province:$scope.$parent.treeViewDataSource[0].province};
        $scope.provinceChange();
        $scope.cityChange();
        $('select').attr('disabled',false)
        //$province.empty().append('<option value="0">请选择</option>')
        //$city.empty().append('<option value="0">请选择</option>')
        //$area.empty().append('<option value="0">请选择</option>')
        //$street.empty().append('<option value="0">请选择</option>')
        //$committee.empty().append('<option value="0">请选择</option>')
        var responseData = JSON.parse(sessionStorage.getItem("areainfo")), $province = $('#provinceData'), $city = $('#cityData'), $area = $('#areaData'), $street = $('#streetData'), $committee = $('#committeeData')
        $.each(responseData.data.regionList, function(index,val){
            if(val.levelType == 1){
                $("<option value="+val.id+" data-parentId="+val.parentId+">"+val.name+"</option>").appendTo($province)
            }
        })
        $province.on('change',function(){
            var id = $(this).val();
            $city.empty().append('<option value="0">请选择</option>')
            $area.empty().append('<option value="0">请选择</option>')
            $street.empty().append('<option value="0">请选择</option>')
            $committee.empty().append('<option value="0">请选择</option>')
            if(id == 310000){
                $('.street-box').fadeIn()
            }else{
                $('.street-box').fadeOut()
            }
            $.each(responseData.data.regionList, function(index,val){
                if(val.parentId == id && val.levelType == 2) {
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($city)
                }
            })
            $('input[name="jurisdiction"]').val(id)
        })
        $city.on('change',function(){
            var id = $(this).val();
            $area.empty().append('<option value="0">请选择</option>')
            $street.empty().append('<option value="0">请选择</option>')
            $committee.empty().append('<option value="0">请选择</option>')
            $.each(responseData.data.regionList, function(index,val){
                if(val.parentId == id && val.levelType == 3) {
                    $("<option value=" + val.id + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($area)
                }
            })
            $('input[name="jurisdiction"]').val(id)
        })
        $area.on('change',function(){
            var id = $(this).val();
            $street.empty().append('<option value="0">请选择</option>')
            $committee.empty().append('<option value="0">请选择</option>')
            $.each(responseData.data.countyList, function(index,val){
                if(val.parentId == id && val.countrysideType == 0) {
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($street)
                }
            })
            $('input[name="jurisdiction"]').val(id)
        })
        $street.on('change',function(){
            var id = $(this).val();
            $committee.empty().append('<option value="0">请选择</option>')
            $.each(responseData.data.countyList, function(index,val){
                if(val.parentId == id && val.countrysideType != 0) {
                    $("<option value=" + val.code + " data-parentId=" + val.parentId + ">" + val.name + "</option>").appendTo($committee)
                }
            })
            $('input[name="jurisdiction"]').val(id)
        })
        $committee.on('change',function(){
            var id = $(this).val();
            $('input[name="jurisdiction"]').val(id)
        })
    };
    $scope.provinceChange = function(type){
        $scope.currCityList = city.filter(function (item) {
            return item.ProID == $scope.orgInfo.province;
        });
        if(type != "view"){
            $scope.orgInfo.city = $scope.currCityList[0].CityID;
            $scope.cityChange();
        }
    };
    $scope.cityChange = function(type){
        $scope.currDistrictList = District.filter(function (item) {
            return item.CityID == $scope.orgInfo.city;
        });
        if(type != "view"){
            $scope.orgInfo.county = $scope.currDistrictList[0].Id;
        }
    }
}]);
/**
 * Created by cjd on 2016/6/7.
 */
angular.module("app").controller("org.managerList.Ctrl", ["$scope", "$http", "User", function ($scope, $http, User) {
    $scope.managerGridConfig = {
        bindingOptions: {
            selectedRowKeys: "selectedItems",
            dataSource: "managerGridConfig.dataSource"
        },
        twoWayBindingEnabled: false,
        searchPanel: {
            visible: true,
            width: 200,
            placeholder: "输入关键字进行查询"
        },
        paging: {
            pageSize: 15
        },
        groupPanel: {
            visible: true,
            emptyPanelText: "拖动列名进行分组和排序"
        },
        hoverStateEnabled: true,
        showBorders: true,
        showRowLines: true,
        rowAlternationEnabled: true,
        noDataText: "没有数据",
        columns: [{
            dataField: "userName",
            alignment: "center",
            caption: "用户名"
        }, {
            dataField: "phone",
            alignment: "center",
            caption: "手机号"
        }, {
            dataField: "certificateType",
            alignment: "center",
            width: 100,
            cellTemplate: "certificateTypeCellTemplate",
            caption: "证件类型"
        }, {
            dataField: "certificateCode",
            alignment: "center",
            caption: "证件号码"
        }, {
            dataField: "status",
            alignment: "center",
            cellTemplate: "statusCellTemplate",
            width: 60,
            caption: "状态"
        }, {
            dataField: "operation",
            alignment: "center",
            cellTemplate: "operationCellTemplate",
            caption: "操作"
        }]
    };
    $scope.orgParent = $scope.$parent.treeViewDataSource[0].orgId;
    $scope.getList = function (orgId) {
        User.getList({}, {orgId: orgId}, function (data) {
            if (data.statusCode == 0) {
                $scope.managerGridConfig.dataSource = data.data;
            }
        });
    };
    $scope.updateManagerStatus = function (managerInfo) {
        User.updateStatus({}, {userId: managerInfo.userId}, function (data) {
            if (data.statusCode == 0) {
                if (managerInfo.status == 10) {
                    managerInfo.status = 20;
                }
                else {
                    managerInfo.status = 10;
                }
                alert("更新成功!")
            }
            else {
                alert(data.statusMessage)
            }
        });
    };
    $scope.treeViewConfig = angular.copy($scope.$parent.treeViewConfig);
    $scope.treeViewConfig.onItemClick = function (e) {
        $scope.getList(e.itemData.orgId);
        $scope.orgParent = e.itemData.orgId;
        $scope.managerInfo = {};
    };
    $scope.showManagerInfo = function (managerInfo) {
        $scope.managerInfo = managerInfo;
        $scope.type = "view";
    };
    $scope.editManagerInfo = function (managerInfo) {
        $scope.managerInfo = managerInfo;
        $scope.type = "edit";
    };
    $scope.saveManager = function () {
        if($scope.managerInfo.certificateType == 1 && !/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/.test($scope.managerInfo.certificateCode)){
            alert("请输入正确的身份证号!");
            return;
        }
        // else if($scope.managerInfo.certificateType == 2 && !/^1[45][0-9]{7}|G[0-9]{8}|P[0-9]{7}|S[0-9]{7,8}|D[0-9]+$/.test($scope.managerInfo.certificateCode)){
        //     alert("请输入正确的护照号码!");
        //     var re1 = /^[a-zA-Z]{5,17}$/;
        //     var re2 = /^[a-zA-Z0-9]{5,17}$/;
        //     return;
        // }
        if(confirm("是否确定执行该操作?")){
            delete $scope.managerInfo.createTime;
            User.saveUser({}, $scope.managerInfo, function (data) {
                if (data.statusCode == 0) {
                    alert("操作成功!");
                    $scope.getList($scope.managerInfo.orgId);
                    $scope.managerInfo = {};
                }
                else if(data.statusCode == -3){
                    alert("手机号已存在!")
                }
                else{
                    alert(data.statusMessage)
                }
            });
        }
    };
    $scope.updateStatus = function (managerInfo) {
        if (confirm("是否确定执行该操作?")) {
            $scope.updateManagerStatus(managerInfo);
        }
    };
    $scope.getList($scope.$parent.treeViewDataSource[0].orgId);
    $scope.createManager = function () {
        $scope.type = "edit";
        $scope.managerInfo = {orgId:$scope.orgParent,status:10,certificateType:1,role:1};
    }
}]);
angular.module("app").controller("passport.logout.Ctrl", ["$scope", "passport","$stateParams", function ($scope,passport,$stateParams) {
    $scope.searchData = {
        cardNo: '',
        orderId: ''
    }
    passport.getList({}, {status: 50}, function (data) {
        $scope.passportInfo = data.data.data
    })
    $scope.search = function () {
        passport.getList({}, {
            status: 50,
            cardNo: $scope.searchData.cardNo || null,
            num: $scope.searchData.orderId || null
        }, function (data) {
            $scope.passportInfo = data.data.data
        })
    }
}]);
angular.module("app").controller("passport.activate.Ctrl", ["$scope", "passport","$stateParams", function ($scope,passport,$stateParams) {
    $scope.searchData = {
        passportId: '',
        phone: ''
    }
    passport.getList({}, {status: 40}, function (data) {
        $scope.passportInfo = data.data.data
    })
    $scope.search = function () {
        passport.getList({}, {
            status: 40,
            passportNo: $scope.searchData.passportId || null,
            mobile: $scope.searchData.phone || null
        }, function (data) {
            $scope.passportInfo = data.data.data
        })
    }
}]);
angular.module("app").controller("passport.make.Ctrl", ["$scope", "passport", "$state", "$stateParams", function ($scope,passport,$state,$stateParams) {
    $scope.searchData = {
        cardId: '',
        orderId: ''
    }
    passport.getList({}, {status: 10}, function (data) {
        $scope.passportInfo = data.data.data
    })
    $scope.search = function () {
        passport.getList({}, {status: 10, cardNo: $scope.searchData.cardId || null, num: $scope.searchData.orderId || null}, function (data) {
            $scope.passportInfo = data.data.data
        })
    }
    passport.getDistrict({}, {}, function (data) {
        $scope.districtInfo = data.data
    })
    $scope.districtChange = function () {
        passport.getAddress({}, {area: $scope.districtName}, function (data) {
            $scope.addressInfo = data.data.data
        })
    }
    $scope.allotAddress = function () {
        passport.allotAddress({}, {passportId: Number($stateParams.id), addressId: $scope.addressId}, function (data) {
            alert(data.statusMessage)
            $state.go('home.passport.make')
        })
    }
}])
angular.module("app").controller("passport.send.Ctrl", ["$scope", "passport","$stateParams", function ($scope,passport,$stateParams) {
    $scope.searchData = {
        cardId: '',
        orderId: ''
    }
    passport.getList({}, {status: 20}, function (data) {
        $scope.passportInfo = data.data.data
    })
    $scope.search = function () {
        passport.getList({}, {status: 20, cardNo: $scope.searchData.cardId || null, num: $scope.searchData.orderId || null}, function (data) {
            $scope.passportInfo = data.data.data
        })
    }
}]);
angular.module("app").controller("passport.sent.Ctrl", ["$scope", "passport","$stateParams", function ($scope,passport,$stateParams) {
    $scope.searchData = {
        passportId: '',
        sentDate: '',
        addr: ''
    }
    passport.sentList({}, {status: 30}, function (data) {
        $scope.passportInfo = data.data.data
    })
    $scope.search = function () {
        passport.sentList({}, {
            status: 30,
            passportNo: $scope.searchData.passportId || null,
            signDate: $scope.searchData.sentDate || null,
            baseAddress: $scope.searchData.addr || null
        }, function (data) {
            $scope.passportInfo = data.data.data
        })
    }
}]);
angular.module("app").controller("homeCtrl", ["$scope", "$http", "$state", "$filter", "treeViewDataSource", "orgList", "$timeout", function ($scope, $http, $state, $filter, treeViewDataSource, orgList, $timeout) {
    if (sessionStorage.userInfo) {
        $scope.userInfo = JSON.parse(sessionStorage.userInfo);
    }
    else {
        location.href = "#/login";
    }
    $scope.selectedItems = [];
    $scope.accordionDataSource = [
        {
            id: 1,
            title: "机构管理",
            menus: [{name: "机构列表", value: "home.org.info"}, 
                    {name: "机构维护", value: "home.org.list"}, 
                    {name: "管理员维护",value: "home.org.managerList"}
            ]
        },
        {
            id: 2,
            title: "基地管理",
            menus: [{name: "基地列表", value: "home.group.list"},{name: "挂靠审核",value: "home.group.verify"},{name: "基地审核",value: "home.group.base"}]
        },
        {
            id: 3,
            title: "护照管理",
            menus: [{name: "待制证", value: "home.passport.make"},{name: "待发证",value: "home.passport.send"},{name: "已发证",value: "home.passport.sent"},{name: "已激活", value: "home.passport.activate"},{name: "待注销",value: "home.passport.logout"}]
        },
        {
            id: 4,
            title: "个人设置",
            menus: [{name: "修改密码", value: "home.user.changePassword"},{name: "退出",value: ""}]
        }
    ];
    // if($scope.userInfo.role == 2){
    //     $scope.accordionDataSource.push({
    //         id:3,
    //         title:"系统设置",
    //         menus:[{name:"机构信息设置",value:"home.setting"}]
    //     })
    // }
    $scope.accordionOptions = {
        dataSource: $scope.accordionDataSource,
        animationDuration: 300,
        collapsible: true,
        bindingOptions: {
            selectedItems: "selectedItems"
        }
    };

    $scope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) {
        if (toState.name.indexOf("org") > 0) {
            $scope.selectedItems = [$scope.accordionDataSource[0]];
        }
        else if (toState.name.indexOf("group") > 0) {
            $scope.selectedItems = [$scope.accordionDataSource[1]];
        }
        else if(toState.name.indexOf("user") > 0){
            $scope.selectedItems = [$scope.accordionDataSource[2]];
        }
    });

    $scope.logout = function () {
        if (confirm("确定要退出吗?")) {
            sessionStorage.clear();
            location.href = "#/login";
        }
    };
    $scope.eventStop = function ($event) {
        $event.stopPropagation();
    };
    $scope.goBack = function () {
        history.back();
    };
    $scope.transformTreeData = function (data) {
        var arr = [];
        var obj = {};
        data.forEach(function (item) {
            item.href = item.orgId;
            item.id = item.orgId;
            item.text = item.orgName;
            item.expanded = true;
            obj[item.orgId] = item;
            if (item.orgId == $scope.userInfo.orgId) {
                arr.push(item);
            }
            else if (item.orgParent) {
                if (!obj[item.orgParent].items) {
                    obj[item.orgParent].items = [];
                }
                item.expanded = false;
                obj[item.orgParent].items.push(item);
            }
        });
        return arr;
    };
    $scope.city = city;
    $scope.District = District;
    $scope.province = province;

    //District.forEach(function(item){
    //    $scope.District[item.Id] = item;
    //});
    //city.forEach(function(item){
    //    $scope.city[item.CityID] = item;
    //});
    //province.forEach(function(item){
    //    $scope.province[item.ProID] = item;
    //});

    $scope.treeViewConfig = {
        bindingOptions: {
            dataSource: "treeViewConfig.dataSource"
        },
        expandAllEnabled: true
    };
    $scope.treeViewDataSource = $scope.transformTreeData(treeViewDataSource.data);
    $scope.treeViewDataSource[0].selected = true;
    $scope.treeViewConfig.dataSource = $scope.treeViewDataSource;
    $scope.orgList = {};
    orgList.data.forEach(function (item) {
        $scope.orgList[item.orgId] = item;
    });
    
    $scope.verifyTabs = {"0":true,"2":false,"-1":false};
}]);
/**
 * Created by cjd on 2016/5/4.
 */
angular.module("app").controller("loginCtrl", ["$scope", "$http", '$timeout', "$state", "User", function ($scope, $http, $timeout, $state, User) {
    if(sessionStorage.userInfo){
        $state.go("home.welcome");//转跳到欢迎页
    }
    else{
        $scope.phone = "";// 账号
        $scope.password = "";//密码

        if (localStorage.remenberName) {//如果之前有记录账号，则显示账号
            $scope.remenberName = true;
            $scope.phone = localStorage.remenberName;
        }

        $scope.login = function () {//登录函数
            sessionStorage.clear();
            User.Login({}, {phone: $scope.phone, password: $scope.password}, function (data) {
                /*登录成功，并记录账号时，将账号记录到 localStorage
                 *如果取消勾选，清空localStorage
                 */
                if (data.statusCode == 0) {
                    sessionStorage.userInfo = JSON.stringify(data.data);
                    $state.go("home.welcome");//转跳到欢迎页
                }else if(data.statusCode == -9){
                    alert("用户被冻结!")
                }else if(data.statusCode == -10){
                    alert("组织被冻结!")
                }else {
                    alert("用户名密码错误!")
                }
            })
        }
    }
}]);
/**
 * Created by cjd on 2016/6/9.
 */
angular.module("app").controller("resetPassword.Ctrl", ["$scope", "$interval", "User", function ($scope, $interval, User) {
    $scope.resetPassword = function () {
        User.resetPassword({}, {
            password: $scope.password,
            code: $scope.checkCode,
            phone: $scope.phone
        }, function (data) {
            if (data.statusCode == 0) {
                alert("密码重置成功,请重新登录!");
                sessionStorage.clear();
                location.href = "#/login";
            } else {
                alert("重置密码出错,请重试!")
            }
        })
    };
    $scope.sendSMS = function () {
        if (!$scope.phone || $scope.phone.length == 0) {
            alert("手机号不能为空!");
            return;
        }
        if($scope.cd != "获取验证码"){
            return;
        }
        User.sendSMS({}, {phone: $scope.phone}, function (data) {
            if (data.statusCode == 0) {
                $scope.count = 60;
                $scope.timer = $interval(function () {
                    if ($scope.count == 0) {
                        $scope.cd = "获取验证码";
                        $interval.cancel($scope.timer);
                    }
                    else {
                        $scope.count--;
                        $scope.cd = "剩余" + $scope.count + "秒";
                    }
                }, 1000)
            }
            else if (data.statusCode == -2) {
                alert("该手机号不存在,请重新输入!")
            }
            else {
                alert(data.statusMessage)
            }
        })
    };
    $scope.cd = "获取验证码";
}]);